package org.crawutils;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
 * 读取请求配置文件，默认放在classpath下的agent下
 * 
 * @author duyf
 * 
 */
public class RequestConfig {

	private static RequestConfig requestConfig = new RequestConfig();
	public static final String STEPID="stepId";
	public static final String STEPFLAG="stepFlag";
	public static final String ERROPAGE="erroPage";
	public static final String COOKIES="cookies";
	public static final String ISADDCOOKIEBYSESSION="isAddCookieBySession";
	private RequestConfig() {
		try {
			loadAgentConfFile();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public static RequestConfig getInstance() {
		return requestConfig;
	}

	
	private  Map<String, Document> map = new ConcurrentHashMap<String, Document>();
	private Map<String, Long> lastModifyDateMap = new ConcurrentHashMap<String, Long>();
	private String configPath=Thread.currentThread().getContextClassLoader().getResource("").getPath()+"agent";
	public  void loadAgentConfFile() throws DocumentException {
		// 初始化所有的 跟采集有关的配置文件 缓存起来
		File file = new File(configPath);
		if (file != null) {
			// 获取所有网站的配置文件
			File files[] = file.listFiles();
			for (File file2 : files) {
				SAXReader reader = new SAXReader();
				Document doc = reader.read(file2);
				// 用文件名对 对应的document 对象保存
				map.put(file2.getName(), doc);
				// 保存文件的最后修改时间,用于后面判断如果有修改的话从新加载文件
				lastModifyDateMap.put(file2.getName(), file2.lastModified());
			}
		}
	}
	
	public Long getLastModifyDate(String filename){
		return lastModifyDateMap.get(filename);
	}
	
	public Document getDocument(String filename){
		return map.get(filename);
	}

	public String getConfigPath() {
		return configPath;
	}
}
